package com.shxy.rlzy.service.impl;

import cn.hutool.system.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shxy.rlzy.entity.Depart;
import com.shxy.rlzy.entity.EmployeeInfo;
import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.mapper.DepartMapper;
import com.shxy.rlzy.mapper.EmployeeInfoMapper;
import com.shxy.rlzy.mapper.UserMapper;
import com.shxy.rlzy.service.IDepartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tanhao
 * @since 2021-09-23
 */
@Service
public class DepartServiceImpl extends ServiceImpl<DepartMapper, Depart> implements IDepartService {
    @Autowired
    private EmployeeInfoMapper employeeInfoMapper;
    @Autowired
    private DepartMapper departMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    public void setEmployeeInfoMapper(EmployeeInfoMapper employeeInfoMapper) {
        this.employeeInfoMapper = employeeInfoMapper;
    }
    @Autowired
    public void setDepartMapper(DepartMapper departMapper) {
        this.departMapper = departMapper;
    }

    @Override
    public boolean exist(Depart depart) {
        // 首先查找名称相同的
        QueryWrapper<Depart> qw = new QueryWrapper<Depart>().eq("name", depart.getName());
        // 如果是已存在的用户，判断id是否不同
        if(depart.getId() != null && depart.getId() > 0) {
            qw = qw.ne("id", depart.getId());
        }
        return this.count(qw) > 0;
    }

    @Override
    public boolean deleteDepartById(Long id) {
        Integer n = employeeInfoMapper.selectCount(new QueryWrapper<EmployeeInfo>().eq("depart_id", id));
        if(n > 0) {
            throw new RuntimeException("删除部门前，请先移除全部部门员工");
        }
        return this.removeById(id);
    }

    @Override
    public boolean setClerk(Long id, Long clerkId) {
        return departMapper.setClerk(id, clerkId) > 0;
    }

    @Override
    public List<Depart> getSalaryDeparts() {
        QueryWrapper<Depart> qw = new QueryWrapper<>();
        qw.eq("has_bonus", 1);
        return departMapper.selectList(qw);
    }

    @Override
    public User getDepartClerk(Long departId) {
        return departMapper.getDepartClerk(departId);
    }
}
